/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.mergesort;

/**
 *
 * @author vlad
 */
class SortTask implements Runnable {
    
    int[] array;
    int left;
    int right;
    
    public SortTask(int[] array, int left, int right) {
        if(array == null) {
            throw new NullPointerException("Null array passed to sort");
        }
        this.array = array;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        if(left < right) {
            int median = (left + right) / 2;
            Thread t = new Thread(new SortTask(array, left, median));
            t.start();
            (new SortTask(array, median + 1, right)).run();
            try {
                t.join();
            } catch(InterruptedException e) {
                System.out.println("Sorting failed");
            }
            int[] tempArray = new int[right - left + 1];
            (new Merge(array,left, median, median + 1, right,
                    tempArray, 0)).run();
            System.arraycopy(tempArray, 0, array, left, tempArray.length);
        }
    }
    
}
